package com.totoro.rabbitmq.producer;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by Administrator on 2017/9/14.
 */
@Service
public class SendService {
        @Resource
        private RabbitTemplate rabbitTemplate ;
//        @Resource
//        private RabbitMessagingTemplate rabbitMessagingTemplate ;
//        @Resource
//        private AmqpTemplate amqpTemplate ;

        /**
         * 广播模式（fanout）发送到fanout类型的exchange消息
         * 因为没有routing key, 设置为null
         * @param exchange
         * @param msg
         */
    public void sendMsgByFanout(String exchange, String msg){
        this.rabbitTemplate.convertAndSend(exchange, null, msg);
    }

    /**
     * 匹配RoutingKey发送消息。direct、topic两种类型都可以通过该方式发送消息
     * @param exchange
     * @param routingKey
     * @param msg
     */
    public void sendMsgByDirectOrTopic(String exchange, String routingKey, String msg){
        this.rabbitTemplate.convertAndSend(exchange , routingKey, msg);
    }

    /**
     * 发送消息到headers模式的exchange
     */
    public void sendMsgByHeaders(String exchange, String param, String value){
        MessageProperties messageProperties = new MessageProperties() ;
        messageProperties.setHeader("to","Niki");
        messageProperties.setHeader("opt","add");
        Message message = new Message(value.getBytes(), messageProperties) ;
        this.rabbitTemplate.convertAndSend(exchange, null, message);
    }
}
